#!/usr/bin/env python
"""
自动化部署脚本 - 适用于不同机器的快速部署
"""
import os
import sys
import socket
import subprocess
import platform
from pathlib import Path


def get_system_info():
    """获取系统信息"""
    info = {
        'platform': platform.system(),
        'python_version': sys.version,
        'hostname': socket.gethostname(),
        'ip_addresses': []
    }
    
    try:
        # 获取所有IP地址
        hostname = socket.gethostname()
        local_ip = socket.gethostbyname(hostname)
        info['ip_addresses'].append(local_ip)
        
        # 尝试获取更多IP
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.connect(("8.8.8.8", 80))
            primary_ip = s.getsockname()[0]
            if primary_ip not in info['ip_addresses']:
                info['ip_addresses'].append(primary_ip)
    except:
        pass
    
    return info


def install_dependencies():
    """安装项目依赖"""
    print("📦 安装项目依赖...")
    
    try:
        # 升级pip
        subprocess.run([sys.executable, '-m', 'pip', 'install', '--upgrade', 'pip'], check=True)
        
        # 安装基础依赖
        packages = [
            'Django==3.2.25',  # 兼容Python 3.6+
            'apscheduler==3.9.1',
            'djangorestframework==3.14.0',
            'sqlalchemy==1.4.53',
            'requests',  # 用于获取公网IP
        ]
        
        # 尝试安装netifaces（网络接口工具）
        try:
            subprocess.run([sys.executable, '-m', 'pip', 'install', 'netifaces'], check=True)
            packages.append('netifaces')
        except:
            print("⚠️  netifaces 安装失败，将使用备用方法获取IP")
        
        for package in packages:
            print(f"   安装 {package}...")
            subprocess.run([sys.executable, '-m', 'pip', 'install', package], check=True)
        
        print("✅ 依赖安装完成")
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖安装失败: {e}")
        return False


def setup_firewall(port=8005):
    """设置防火墙规则（仅提示）"""
    print(f"\n🔥 防火墙配置提示 (端口 {port}):")
    
    system = platform.system().lower()
    
    if system == 'linux':
        print("📋 Linux 防火墙命令:")
        print(f"   # UFW (Ubuntu/Debian)")
        print(f"   sudo ufw allow {port}")
        print(f"   sudo ufw status")
        print()
        print(f"   # Firewalld (CentOS/RHEL)")
        print(f"   sudo firewall-cmd --permanent --add-port={port}/tcp")
        print(f"   sudo firewall-cmd --reload")
        print()
        print(f"   # Iptables")
        print(f"   sudo iptables -A INPUT -p tcp --dport {port} -j ACCEPT")
        
    elif system == 'windows':
        print("📋 Windows 防火墙命令:")
        print(f"   netsh advfirewall firewall add rule name=\"Django-{port}\" dir=in action=allow protocol=TCP localport={port}")
        
    elif system == 'darwin':  # macOS
        print("📋 macOS 防火墙配置:")
        print("   在 系统偏好设置 > 安全性与隐私 > 防火墙 中添加应用")
    
    print("\n☁️  云服务器额外配置:")
    print("   • 阿里云: 安全组规则 - 入方向 - 添加规则")
    print("   • 腾讯云: 安全组 - 入站规则 - 添加规则")
    print("   • AWS: Security Groups - Inbound Rules")
    print("   • Azure: Network Security Group - Inbound rules")


def create_startup_script(port=8005):
    """创建启动脚本"""
    system_info = get_system_info()
    
    # 生成启动脚本内容
    script_content = f"""#!/bin/bash
# Django APScheduler 启动脚本
# 自动生成 - {socket.gethostname()}

echo "🚀 启动 Django APScheduler 任务调度系统"
echo "📍 主机: {system_info['hostname']}"
echo "🐍 Python: {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
echo "🌐 IP地址: {', '.join(system_info['ip_addresses'])}"
echo "🔌 端口: {port}"
echo ""

# 激活虚拟环境（如果存在）
if [ -d "venv" ]; then
    echo "📦 激活虚拟环境..."
    source venv/bin/activate
fi

# 运行数据库迁移
echo "🔧 运行数据库迁移..."
python manage.py makemigrations
python manage.py migrate

# 创建超级用户（如果不存在）
echo "👤 检查超级用户..."
python -c "
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_scheduler.settings')
import django
django.setup()
from django.contrib.auth.models import User
if not User.objects.filter(is_superuser=True).exists():
    User.objects.create_superuser('admin', 'admin@example.com', 'admin123')
    print('✅ 超级用户已创建: admin/admin123')
else:
    print('✅ 超级用户已存在')
"

echo ""
echo "🌐 系统访问地址:"
"""

    # 添加访问地址
    for ip in system_info['ip_addresses']:
        script_content += f'echo "   http://{ip}:{port}/admin"\n'
    
    script_content += f"""
echo ""
echo "✅ 启动完成！按 Ctrl+C 停止服务"
echo ""

# 启动Django服务器
python manage.py runserver 0.0.0.0:{port}
"""
    
    # 写入启动脚本
    script_path = Path('start_server.sh')
    with open(script_path, 'w', encoding='utf-8') as f:
        f.write(script_content)
    
    # 设置执行权限
    if platform.system() != 'Windows':
        os.chmod(script_path, 0o755)
    
    print(f"✅ 启动脚本已创建: {script_path}")
    return script_path


def create_service_file(port=8005):
    """创建系统服务文件（Linux）"""
    if platform.system().lower() != 'linux':
        return
    
    system_info = get_system_info()
    project_path = Path(__file__).parent.absolute()
    python_path = sys.executable
    
    service_content = f"""[Unit]
Description=Django APScheduler Task Scheduler
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory={project_path}
Environment=DJANGO_SETTINGS_MODULE=django_scheduler.settings
ExecStart={python_path} manage.py runserver 0.0.0.0:{port}
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
"""
    
    service_path = Path('django-scheduler.service')
    with open(service_path, 'w', encoding='utf-8') as f:
        f.write(service_content)
    
    print(f"✅ 系统服务文件已创建: {service_path}")
    print("📋 安装服务命令:")
    print(f"   sudo cp {service_path} /etc/systemd/system/")
    print("   sudo systemctl daemon-reload")
    print("   sudo systemctl enable django-scheduler")
    print("   sudo systemctl start django-scheduler")
    print("   sudo systemctl status django-scheduler")


def main():
    """主函数"""
    print("🚀 Django APScheduler 自动部署脚本")
    print("=" * 50)
    
    # 获取系统信息
    system_info = get_system_info()
    print("📊 系统信息:")
    print(f"   操作系统: {system_info['platform']}")
    print(f"   主机名: {system_info['hostname']}")
    print(f"   Python版本: {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}")
    print(f"   IP地址: {', '.join(system_info['ip_addresses'])}")
    print()
    
    # 获取端口号
    port = 8005
    if len(sys.argv) > 1:
        try:
            port = int(sys.argv[1])
        except ValueError:
            print("⚠️  端口号必须是数字，使用默认端口 8005")
    
    # 安装依赖
    if not install_dependencies():
        print("❌ 部署失败")
        sys.exit(1)
    
    # 创建启动脚本
    script_path = create_startup_script(port)
    
    # 创建系统服务文件
    create_service_file(port)
    
    # 防火墙配置提示
    setup_firewall(port)
    
    print("\n" + "=" * 50)
    print("🎉 自动部署完成！")
    print("=" * 50)
    
    print(f"\n🚀 快速启动:")
    if platform.system() == 'Windows':
        print(f"   python start_system.py {port}")
    else:
        print(f"   ./start_server.sh")
        print(f"   或者: python start_system.py {port}")
    
    print(f"\n🌐 访问地址:")
    for ip in system_info['ip_addresses']:
        print(f"   http://{ip}:{port}/admin")
    
    print(f"\n👤 默认账号: admin / admin123")
    
    print(f"\n📝 下一步:")
    print("   1. 配置防火墙规则")
    print("   2. 启动服务")
    print("   3. 浏览器访问管理界面")
    print("   4. 修改默认密码")


if __name__ == '__main__':
    main()